package controller

import (
	"admin/contrib/session"
	"admin/contrib/validator"
	"admin/model"
	"common/helper"
	"encoding/json"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
)

type AdminController struct{}

type adminInsert struct {
	GroupID       string `json:"group_id" cbor:"group_id"`
	Name          string `json:"name" cbor:"name"`
	Password      string `json:"password" cbor:"password"`
	Seamo         string `json:"seamo" cbor:"seamo"`
	State         int    `json:"state" cbor:"state"`
	ImportantInfo int    `cbor:"important_info" db:"important_info" json:"important_info"`
	SysConfigInfo int    `cbor:"sysconfig_info" db:"sysconfig_info" json:"sysconfig_info"`
}

func (that *AdminController) Insert(ctx *fasthttp.RequestCtx) {

	param := adminInsert{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	// 判断用户名是否已经存在
	if model.AdminExist(g.Ex{"name": param.Name}) {
		helper.RetData(ctx, false, "用户已存在")
		return
	}

	admin := session.AdminGet(ctx)

	now := uint32(ctx.Time().Unix())
	record := model.Admin{
		GroupID:       param.GroupID,
		Name:          param.Name,
		Pwd:           param.Password,
		Seamo:         param.Seamo,
		State:         param.State,
		CreateAt:      now,
		CreatedUid:    admin["id"],
		CreatedName:   admin["name"],
		UpdatedAt:     now,
		UpdatedUid:    admin["id"],
		UpdatedName:   admin["name"],
		ImportantInfo: param.ImportantInfo,
		SysConfigInfo: param.SysConfigInfo,
	}
	err = model.AdminInsert(record)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "succeed")
}

type adminUpdate struct {
	ID            string `json:"id" cbor:"id"`
	GroupID       string `json:"group_id" cbor:"group_id"`
	Seamo         string `json:"seamo" cbor:"seamo"`
	Password      string `json:"password" cbor:"password"`
	State         int    `json:"state" cbor:"state"`
	ImportantInfo int    `cbor:"important_info" db:"important_info" json:"important_info"`
	SysConfigInfo int    `cbor:"sysconfig_info" db:"sysconfig_info" json:"sysconfig_info"`
}

func (that *AdminController) Update(ctx *fasthttp.RequestCtx) {

	param := adminUpdate{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.State != 0 && param.State != 1 {
		helper.RetData(ctx, false, "状态错误")
		return
	}

	if !validator.CtypeDigit(param.ID) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	if !validator.CtypeDigit(param.GroupID) {
		helper.RetData(ctx, false, helper.GroupIDErr)
		return
	}

	if len(param.Password) > 0 {
		if !validator.CheckAPassword(param.Password, 5, 20) {
			helper.RetData(ctx, false, helper.PasswordFMTErr)
			return
		}
	}

	record := g.Record{}
	//if param.Seamo != "" {
	//	_, err := base32.StdEncoding.DecodeString(param.Seamo)
	//	if err != nil {
	//		helper.RetData(ctx, false, helper.SeamoErr)
	//		return
	//	}
	//
	//	record["seamo"] = param.Seamo
	//}

	admin := session.AdminGet(ctx)
	if param.Seamo == "unbind" {
		record["Seamo"] = param.Seamo
	}

	record["state"] = param.State
	record["important_info"] = param.ImportantInfo
	record["sysconfig_info"] = param.SysConfigInfo
	record["group_id"] = param.GroupID
	record["updated_at"] = ctx.Time().Unix()
	record["updated_uid"] = admin["id"]
	record["updated_name"] = admin["name"]
	err = model.AdminUpdate(admin["id"], admin["name"], param.ID, param.Password, param.GroupID, record)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "")
}

func (that *AdminController) UpdateState(ctx *fasthttp.RequestCtx) {

	id := string(ctx.QueryArgs().Peek("id"))
	state := string(ctx.QueryArgs().Peek("state"))

	s := map[string]bool{
		"0": true,
		"1": true,
	}
	if _, ok := s[state]; !ok {
		helper.RetData(ctx, false, "状态错误")
		return
	}

	if !validator.CtypeDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	admin := session.AdminGet(ctx)

	err := model.AdminUpdateState(admin["id"], admin["name"], id, state)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *AdminController) List(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	name := string(ctx.QueryArgs().Peek("name"))
	state := string(ctx.QueryArgs().Peek("state"))
	groupID := string(ctx.QueryArgs().Peek("groupid"))

	if page < 1 {
		page = 1
	}
	ex := g.Ex{}

	if name != "" {
		if !validator.CheckAName(name, 5, 20) {
			helper.RetData(ctx, false, helper.AdminNameErr)
			return
		}

		ex["name"] = name
	}

	if state == "0" || state == "1" {
		ex["state"] = state
	}

	if groupID != "" {
		if !validator.CtypeDigit(groupID) {
			helper.RetData(ctx, false, helper.GroupIDErr)
			return
		}

		ex["group_id"] = groupID
	}

	admin := session.AdminGet(ctx)
	adminifo, _ := model.GetAdminInfoById(admin["id"])
	data, err := model.AdminList(adminifo, uint(page), 10, ex)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	for key, _ := range data.D {
		(data.D)[key].Pwd = ""
		(data.D)[key].Seamo = ""
	}
	helper.RetData(ctx, true, data)
}

type adminLogin struct {
	Username string `json:"username" cbor:"username"`
	Pwd      string `json:"pwd" cbor:"pwd"`
	Seamo    string `json:"seamo" cbor:"seamo"`
}
